<?php
/**
* Created by PhpStorm.
* User: xcx
* Date: 2017/06/01
* Time: 12:01
*/
class Service_User extends FController{

    /**
     * 获取会员详情信息
     * @param $openid
     * @return array|bool|mixed|null|string
     */
    public static function getUserInfo($openid){
        $key = 'user_datail_' . $openid;
        $userDetail = FCache::get($key);
        if(!$userDetail){
            $userT = new FTable('user','','xhs_slave');
            $userDetail = $userT->where(array('openid'=>$openid))->find();
            FCache::set($key,$userDetail,3600);
        }
        return $userDetail;
    }

    /**
     * 会员是否关注公众号
     * @param $openid
     * @return bool
     */
    public static function isSubscribe($openid){
        $userDetail = self::getUserInfo($openid);
        if($userDetail['subscribe'] == 1)
            return true;
        else
            return false;
    }

    /**
     * 清空会员详情缓存
     * @param $openid
     */
    public static function clearUserInfoCache($openid){
        $key = 'user_datail_' . $openid;
        FCache::delete($key);
    }

    /**
     * 保存会员
     * @param $result
     * @param $user
     * @return array
     */
    public static function saveUser($result,$user = array()){
        $userT = new FTable('user','','xhs_master');
        $user['username'] = $result['nickname'];
        $user['avatar'] = $result['headimgurl'];
        $user['openid'] = $result['openid'];
        $user['gender'] = $result['sex'];
        if(isset($result['subscribe'])) $user['subscribe'] = 1;
        if(isset($result['subscribe_time'])) $user['subscribe_time'] = $result['subscribe_time'];
        if(isset($result['last_operation_time'])) $user['last_operation_time'] = $result['last_operation_time'];
        if(isset($result['city'])) $user['city'] = $result['city'];
        if(isset($result['province'])) $user['province'] = $result['province'];
        if(empty($user['uid'])){
            $user['reg_time'] = time();
            $user['create_time'] = date('Y-m-d H:i:s');
            $user['login_time'] = time();
            $user['login_count'] = 1;
            $uid = $userT->insert($user);
        }else{
            $uid = $user['uid'];
            unset($user['uid']);
            $userT->where(array('uid'=>$user['uid']))->save($user);
            self::clearUserInfoCache($result['openid']);
        }

        $user['uid'] = $uid;
        return $user;
    }

    /**
     * 根据openid取消关注
     * @param $openid
     * @return bool
     */
    public static function cancelSubscribe($openid)
    {
        $table = new FTable('user','','xhs_master');
        $result = $table->where(array('openid' => $openid))->update1(array('subscribe' => 0));
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 激活关注
     * @param $openid
     * @return bool
     */
    public static function activationSubscribe($openid)
    {
        $table = new FTable('user','','xhs_master');
        $result = $table->where(array('openid' => $openid))->update1(array('subscribe' => 1,'subscribe_time'=>time()));
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据用户ID更新最后操作时间
     * @param $openid
     * @return bool
     */
    public static function updateLastTimeByUid($openid)
    {
        $table = new FTable('user','','xhs_master');
        $result = $table->where(array('openid' => $openid))->update1(array('last_operation_time' => time() + 60 * 60 * 24 * 2));
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    /*
     * 省份获取
     */
    public static function getProvince(){

        $key = "province_lists_20171027";
//        FCache::delete($key);
        $cache = FCache::get($key);
            if($cache){
                return $cache;
            }else{
                $table = new FTable("privince", "", "xhs_slave");
                $list = $table->fields("id, code, name")->select();
                FCache::set($key, $list, 24*3600*7);
                return $list;
            }
    }

    /*
     * 根据省份获取城市信息
     * @param $provinceCode 省份编码
     */
    public static function getCity($provinceCode){
        $key = "city_list122_{$provinceCode}";
        FCache::delete($key);
        if($provinceCode){
            $cache = FCache::get($key);
            if($cache){
                return $cache;
            }else{
                $table = new FTable("city", "", "xhs_slave");
                $list = $table->fields("id, code, name, provinceCode")->where(array("provinceCode" => $provinceCode))->select();
                if($list){
                    FCache::set($key, $list, 7*24*3600);
                    return $list;
                }else{
                    return false;
                }
            }
        }else{
            return false;
        }
    }

    /*
     * 获取店员信息详情
     * @param $uid 店员id
     */
    public static function getUserDetailAction($uid){
        $key = "clerk_detail_{$uid}";
        if($uid){
            $cache = FCache::get($key);
            if($cache){
                return $cache;
            }else{
                global $_F;
                $uid = $_F['uid'];
                $where = array();
                $where['c.uid'] = $uid;
                $clerkTable = new FTable("clerk", "c", "xhs_slave");
                $data = $clerkTable->fields("c.uid, c.avatar, c.shop_id, c.gender, c.nickname, c.openid, cs.name as shop_name
        , cs.work_status as shop_work_status, cs.address as shop_address, cs.manager as shop_manager")
                    ->leftJoin("chain_shop", "cs", "cs.id=c.shop_id")
                    ->where($where)
                    ->find();
                if($data){
                    FCache::set($key, $data, 7*24*3600);
                    return $data;
                }else{
                    return false;
                }
            }
        }else{
            return false;
        }
    }

    /*
     * 修改连锁店营业状态
     * @param $shop_id  连锁店id
     * @param $work_status 营业状态
     */
    public static function chainStatusModifyAction($shop_id, $status){
        global $_F;
        if($shop_id && $status){
            $chainTable = new FTable("chain_shop", "", "xhs_slave");
            $data = $chainTable->where("id={$shop_id}")->find();
            if($status == 2 && $data['work_status'] == 1){
                $now_time = date("H:i:s", time());
                if($now_time >= $data['start_work_time'] && $now_time<= $data['stop_work_time']){
                    $chainTable = new FTable("chain_shop", "", "xhs_master");
                    $ret = $chainTable->update1(array("work_status" => $status), array("id" => $shop_id));
                    if($ret){
                        $result = array("status" => 200, "success" => "修改营业状态成功!");
                        return $result;
                    }else{
                        $result = array("status" => -3, "error" => "修改营业状态失败!");
                        return $result;
                    }
                }else{
                    $result = array("status" => -1, "error" => "不在营业时间内");
                    return $result;
                }
            }else{
                $chainTable = new FTable("chain_shop", "", "xhs_master");
                $ret = $chainTable->update1(array("work_status" => $status), array("id" => $shop_id));
                if($ret){
                    $result = array("status" => 200, "success" => "修改营业状态成功!");
                    return $result;
                }else{
                    $result = array("status" => -3, "error" => "修改营业状态失败!");
                    return $result;
                }
            }
        }else{
            $result = array("status" => -2, "error" => "参数缺失");
            return $result;
        }


    }

    /*
     * 收入统计
     * @param $shop_id 连锁店id id未空则统计所有的收入
     */
    public static function incomeTjAction($shop_id){
        //$ordersTable = new FTable("orders", "", "xhs_slave");
        $where = array();
        $where['status'] = 5;

        if($shop_id){
            $where['shop_id'] = $shop_id;
        }

        //当天的收入
        $start_time = date("Y-m-d", time()) . " 00:00:00";
        $end_time = date("Y-m-d", time()) . " 23:59:59";
        $where["pay_time"] = array("lte" => $end_time, "gte" => $start_time);
        $todayData = self::incomeSelectAction($where);
        //昨天收入
        $start_time = date("Y-m-d", strtotime("-1 days")) . " 00:00:00";
        $end_time = date("Y-m-d",strtotime("-1 days")) . " 23:59:59";
        $where["pay_time"] = array("lte" => $end_time, "gte" => $start_time);
        $yesterdayData = self::incomeSelectAction($where);

        //本周收入
        $start_time = date("Y-m-d", strtotime("-6 days")) . " 00:00:00";
        $end_time = date("Y-m-d", time()) . " 23:59:59";
        $where["pay_time"] = array("lte" => $end_time, "gte" => $start_time);
        $weekData = self::incomeSelectAction($where);


        //本月收入
        $start_time = date("Y-m-d", strtotime("-29 days")) . " 00:00:00";
        $end_time = date("Y-m-d", time()) . " 23:59:59";
        $where["pay_time"] = array("lte" => $end_time, "gte" => $start_time);
        $monthData = self::incomeSelectAction($where);
        //上月收入
        $start_time = date("Y-m-d", strtotime("-59 days")) . " 00:00:00";
        $end_time = date("Y-m-d", strtotime("-29 days")) . " 23:59:59";
        $where["pay_time"] = array("lte" => $end_time, "gte" => $start_time);
        $lastMonth = self::incomeSelectAction($where);

//        var_dump($where);exit();

        //所有收入
       /* $whereAll = array("status" => 5);
        if($shop_id){
            $whereAll['shop_id'] = $shop_id;
        }*/
        unset($where["pay_time"]);
        $allData = self::incomeSelectAction($where);

        $result = array(
            "today_income" => $todayData,
            "week_income" => $weekData,
            "month_income" => $monthData,
            "all_income" => $allData,
            "yesterday_income"=>$yesterdayData,
            "lastmonth_income"=>$lastMonth,
        );
        return $result;

    }

    /*
     * 收入查询
     * @param $where 条件
     */
    public static function incomeSelectAction($where){
        if($where){
            $ordersTable = new FTable("orders", "", "xhs_slave");
            $data = $ordersTable->fields("sum(pay_price) as pay_price")->where($where)->find();
            $result = $data['pay_price'] ? $data['pay_price'] : 0;
            return $result;
        }else{
            return false;
        }
    }

    /*
     * 订单数量统计
     * @param $shop_id 连锁店id id未空则统计所有的订单数量
     */
    public static function orderTjAction($shop_id){
        global $_F;
        $ordersTable = new FTable("orders", "", "xhs_slave");
        $where = array();
        $where['status'] = 5;

        if($shop_id){
            $where['shop_id'] = $shop_id;
        }

        //当天订单数量
        $start_time = date("Y-m-d", time()) . " 00:00:00";
        $end_time = date("Y-m-d", time()) . " 23:59:59";
        $where["pay_time"] = array("lte" => $end_time, "gte" => $start_time);
        $todayData = self::ordersCountAction($where);
        //本周订单数量
        $start_time = date("Y-m-d", strtotime("-6 days")) . " 00:00:00";
        $end_time = date("Y-m-d", time()) . " 23:59:59";
        $where["pay_time"] = array("lte" => $end_time, "gte" => $start_time);
        $weekData = self::ordersCountAction($where);


        //本月订单数量
        $start_time = date("Y-m-d", strtotime("-29 days")) . " 00:00:00";
        $end_time = date("Y-m-d", time()) . " 23:59:59";
        $where["pay_time"] = array("lte" => $end_time, "gte" => $start_time);
//        var_dump($where);exit();
        $monthData = self::ordersCountAction($where);

        //本周订单数量
        unset($where["pay_time"]);
        $allData = self::ordersCountAction($where);

        $result = array(
            "today_sum" => $todayData,
            "week_sum" => $weekData,
            "month_sum" => $monthData,
            "all_sum" => $allData,
        );
        return $result;
    }

    /*
     * 订单数量查询
     * @param $where 查询条件
     */
    public static function ordersCountAction($where){
        if($where){
            $ordersTable = new FTable("orders", "", "xhs_slave");
            $data = $ordersTable->where($where)->count();
            $result = $data ? $data : 0;
            return $result;
        }else{
            return false;
        }
    }

    /*
     * 收入明细
     * @param $shop_id 连锁店id id未空则为所有的收入明细
     * @param $start_time 开始时间
     * @param $end_time 结束时间
     * @param $page 页码
     */
    public static function incomeDetailAction($shop_id, $start_time, $end_time, $page){
        $where = array();
        if($shop_id){
            $where['shop_id'] = $shop_id;
        }
        if($start_time && $end_time){
            $where["pay_time"] = array("lte" => $end_time, "gte" => $start_time);
        }
        $table = new FTable("orders", "", "xhs_slave");
        $data = $table->fields("*")
            ->where($where)
            ->page($page)
            ->limit(20)
            ->order("auto_id desc")
            ->select();
        if($data){
            return $data;
        }else{
            return false;
        }
    }


    function showMessage($message, $msgType, $url = null)
    {
        echo "<script>alert('{$message}');";
        if ($url) echo "location='{$url}';";
        echo "</script>";
    }

}